package blackjack.client.connection;

import java.io.IOException;
import blackjack.client.ConnectionApplet;

/**
 * waits messages fromServer and does relevant actions
 *
 */
public class ClientListener extends Thread {
	
	ConnectionApplet client;
	
	public ClientListener(ConnectionApplet client){
		this.client = client;
	}
	
	@SuppressWarnings("unchecked")
	public void run() {
		try {
			while (true) { // main tsqkl
				String str = client.getin().readLine(); // blocked...

				client.mainPanel.repaint();
				allClients(str);
				othersCards(str);

				if(str!= null && opgCard(str)!= null) {
					if(who(str).equals(client.getFirst()) && who(str) != null){
						client.esimeneKard.add("CardDeck");
					}
					if(who(str).equals(client.second) && who(str) != null){
						client.teineKard.add("CardDeck");
					}
				}
				error(str);
				
				if(Character.isDigit(str.charAt(0)) == true) {
					client.pickedCards.add(str);//kaart on voetud
					client.points += client.deck.CardStringtoInt(str);//loetakse punkte vastavalt kaardi vaartusele
				}
				synchronized (client.getMessage()) { // lock
					client.message.add(str);
				}
			} // while
		} catch (IOException e) {
		} finally {
			try {
				if (!client.getSocket().isClosed()) {
					client.getSocket().close();
					System.out.println("closed...");
					return;
				}
			} catch (IOException ee) {
			}
		} // finally
	}

	/**
	 * who left
	 * @param str  fromserver string
	 */
	public void error(String str){
		String[] temp = null;

		temp = str.split(" ");

		for(int i =0; i < temp.length ; i++){
			if(temp[i].equals(client.getName()))break;

			if(temp[i].equals("-avarii...")){
				if(temp[i-1].equals(client.getFirst())){
					client.esimeneKard.clear();
					client.first += " left the game ";
					client.esimenesuri++;
				}
				if(temp[i-1].equals(client.getSecond())){
					client.teineKard.clear();
					client.second += " left the game ";
					client.teinesuri++;
				}
				continue;
			}
		}
	}

	/**
	 * 
	 * @param str - serveri poolt saadetav string
	 * @return kas toiesti keegi vottis kaardi
	 */
	public String who(String str){
		String who = null;
		String[] temp = null;
		String delimeter = " ";

		temp = str.split(delimeter);

		for(int i =0; i < temp.length ; i++){
			if(temp[i].equals(client.getName()))break;
			if(temp[i].equals(client.getFirst()))who = client.getFirst();
			if(temp[i].equals(client.getSecond()))who = client.getSecond();
		}
		return who;
	}// run

	/**
	 * Mitu kasutajat tuli mangu
	 * @param str fromServer
	 */
	public void allClients(String str){
		String[] temp = null;
		temp = str.split(" ");
		for(int i =0; i < temp.length ; i++){
			if(temp[i].equals(client.getName()))break;
			if(temp[i].equals("kokku")){
				client.setKokku(temp[i-1]);
				continue;
			}
		}
	}

	/**
	 * Uute kasutajate kohta info leidmine
	 * @param str - fromServer string
	 * @return
	 */
	public String opgCard(String str){
		String res = null;
		String[] temp = null;
		temp = str.split(" ");
		for(int i =0; i < temp.length ; i++){
			if(temp[i].equals(client.getName()))break;
			if(temp[i].equals("done"))res = "done";  
			if(temp[i].equals("lausub:") || temp[i].equals("tuli")){
				if(client.getFirst() == null){
					client.setFirst(temp[i-1]);
				}
				if(client.getSecond() == null){
					if(client.getFirst().equals(temp[i-1]) == false){
						client.setSecond(temp[i-1]);
					}
				}
			}
		}
		return res;
	}

	/**
	 * share cards info
	 * @param str fromServer
	 */
	@SuppressWarnings("unchecked")
	public void othersCards(String str){
		int d = 0;
		int d2 = 0;

		String[] temp = null;
		temp = str.split(" ");

		for(int i =0; i < temp.length ; i++){
			if(temp[i].equals(client.getName()))break;

			if(temp[i].equals("all")){
				if(temp[i-1].equals(client.getFirst())){
					d++;
					client.getEsimeneKard().clear();
					client.param++;
				}
				if(temp[i-1].equals(client.getSecond())){
					d2++;
					client.getTeineKard().clear();
					client.param2++;
				}
				continue;
			}
			if(d != 0)client.getEsimeneKard().add(temp[i]);
			if(d2 != 0)client.getTeineKard().add(temp[i]);
		}
		if(d != 0 || d2 != 0)client.newGame.setEnabled(true);
	}
	
}